import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取session对象
        HttpSession session = request.getSession(true);

        // 设置自定义属性
        session.setAttribute("customAttribute", "Hello from SessionServlet!");

        // 获取session的各个属性值
        String sessionId = session.getId();
        long creationTime = session.getCreationTime();
        boolean isNew = session.isNew();
        long lastAccessedTime = session.getLastAccessedTime();
        int maxInactiveInterval = session.getMaxInactiveInterval();

        // 设置session的失效时间为1分钟
        session.setMaxInactiveInterval(60);

        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        // 获取响应对象的 PrintWriter
        PrintWriter out = response.getWriter();

        // 输出session属性值到响应中
        out.println("<html>");
        out.println("<head><title>Session Information</title></head>");
        out.println("<body>");
        out.println("<h1>Session Information</h1>");
        out.println("<p>Session ID: " + sessionId + "</p>");
        out.println("<p>Creation Time: " + formatDate(creationTime) + "</p>");
        out.println("<p>Is New Session: " + isNew + "</p>");
        out.println("<p>Last Accessed Time: " + formatDate(lastAccessedTime) + "</p>");
        out.println("<p>Max Inactive Interval: " + maxInactiveInterval + " seconds</p>");
        out.println("<p>Custom Attribute Value: " + session.getAttribute("customAttribute") + "</p>");
        out.println("<a href=\"SessionPage1.jsp\">Visit Page 1</a>");
        out.println("<a href=\"SessionPage2.jsp\">Visit Page 2</a>");
        out.println("</body>");
        out.println("</html>");
    }

    private String formatDate(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(time));
    }
}
